package top.lvjp.designMode;

import java.util.Vector;

/** 观察者 */
interface Observer {
    void update(String message);
}

/** 具体观察者 */
class ConcreteObserver implements Observer {
    @Override
    public void update(String message) {
        if("主题更新".equals(message))
        System.out.println("收到!");
    }
}

/** 主题 */
abstract class Subject {
    private Vector<Observer> observers = new Vector<>();

    public void add(Observer observer){
        observers.add(observer);
    }
    public void del(Observer observer){
        observers.remove(observer);
    }
    protected void notify(String newState){
        System.out.println(newState);
        for (Observer o: observers){
            o.update(newState);
        }
    }
}

/** 具体主题 */
class ConcreteSubject extends Subject {
    public void doSomething(String message){
        notify(message);
    }
}

/** 测试 */
public class ObserverTest {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();
        Observer observer = new ConcreteObserver();
        subject.add(observer);
        subject.doSomething("主题更新");
    }
}
